package com.flex.showdoc4j.spring;

import com.flex.showdoc4j.proxy.MockTypeResolver;
import com.flex.showdoc4j.proxy.ServiceMockProxy;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author ganlt
 * @since 2019/08/01 8:36
 */
@Component
public class DocSpringFactoryBean<T> implements FactoryBean<T> {
    private Class<T> interfaceClass;
    private List<MockTypeResolver> mockTypeResolverList = new ArrayList<>();

    public DocSpringFactoryBean() {
        //使用spi扩展解析器
        ServiceLoader<MockTypeResolver> load = ServiceLoader.load(MockTypeResolver.class);
        load.forEach(var -> mockTypeResolverList.add(var));
    }

    public Class<T> getInterfaceClass() {
        return this.interfaceClass;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
    public T getObject() throws Exception {
        return (T) new ServiceMockProxy().proxy(interfaceClass,mockTypeResolverList);
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }

    public void setInterfaceClass(Class<T> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }
}
